﻿using System;
using System.IO;
using System.IO.IsolatedStorage;
using Microsoft.Xna.Framework.Media;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace PictureSearch.AppCode
{
    public static class ImageCommon
    {
        private const string imageDirectory = "GalleryImages";

        public static void SaveToAlbum(string imageName)
        {
            string fileName = string.Format("{0}\\{1}", imageDirectory, imageName);

            using (var iso = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream isostream = iso.OpenFile(fileName, FileMode.Open, FileAccess.Read))
                {
                    MediaLibrary library = new MediaLibrary();

                    // Save the image to the camera roll album.
                    library.SavePicture(imageName, isostream);
                }
            }
        }

        public static string SaveImage(ImageSource imageSource)
        {
            // Create folder if not exsist
            FileCommon.CreateDirectory(imageDirectory);

            // Save image
            BitmapSource bitmap = (BitmapSource)imageSource;

            Guid id = Guid.NewGuid();
           
            string imagePath = string.Format("{0}\\{1}.jpg", imageDirectory, id);
            FileCommon.SaveImage((BitmapImage) bitmap, imagePath);

            return string.Format("{0}.jpg", id);
        }

        public static void DeleteImage(string imageName)
        {
            string fileName = string.Format("{0}\\{1}", imageDirectory, imageName);
            FileCommon.DeleteFile(fileName);
        }

        public static void GetImageData(string imageName, Action<MemoryStream> action)
        {
            string fileName = string.Format("{0}\\{1}", imageDirectory, imageName);
            FileCommon.LoadImage(fileName, action);
        }

        public static string[] GetImageList()
        {
            return FileCommon.GetFilesInDirectory(imageDirectory);
        }
    }
}
